package com.velvetantler.weather.view.mine

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.velvetantler.weather.WeatherApplication
import com.velvetantler.weather.base.BaseBindingFragment
import com.velvetantler.weather.bean.UserInfoResponse
import com.velvetantler.weather.constants.Constants
import com.velvetantler.weather.databinding.FragmentMeBinding
import com.velvetantler.weather.utils.PreferenceUtil
import com.velvetantler.weather.utils.RetrofitClient
import com.velvetantler.weather.view.login.LoginActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MeFragment : BaseBindingFragment<FragmentMeBinding>() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onResume() {
        super.onResume()
        // 获取用户信息
        getUserInfo()
    }

    override fun initBinding(
        inflater: LayoutInflater,
        parent: ViewGroup?
    ): FragmentMeBinding {
        return FragmentMeBinding.inflate(inflater, parent, false)
    }

    override fun initView() {
        // 退出登陆
        logout()
        // 跳转修改头像
        val intent = Intent(requireContext(), UpdateProfileActivity::class.java)
        binding.ivAvatar.setOnClickListener {
            startActivity(intent)
        }
        binding.ivEditAvatar.setOnClickListener {
            startActivity(intent)
        }
    }

    private fun logout() {
        val logout = binding.btnLogout
        logout.setOnClickListener {
            // 退出登陆
            Toast.makeText(requireContext(), "退出登陆", Toast.LENGTH_SHORT).show()
            // 清除token
            PreferenceUtil.getInstance(requireContext()).removeValue(Constants.TOKEN_PREF_KEY)
            // 跳转到登录页面
            startActivity(Intent(requireContext(), LoginActivity::class.java))
            requireActivity().finish()
        }
    }

    /**
     * 获取用户信息并保存
     */
    private var debounceTime = 0L // 防抖时间
    private fun getUserInfo() {
        // 防抖
        val nowTime = System.currentTimeMillis()
        if (nowTime - debounceTime < 2000) {
            Log.e("MeFragment", "getUserInfo: 请稍后再试")
            return
        }
        debounceTime = nowTime

        try {
            lifecycleScope.launch(Dispatchers.Main) {
                try {
                    val response = withContext(Dispatchers.IO) {
                        RetrofitClient.apiServices.getUserInfo()
                    }
                    if (response.code == 10000) {
                        // 处理头像的地址
                        val index = response.data.avatar.indexOf("upload")
                        val avatar = response.data.avatar.substring(index)
                        val userInfo = UserInfoResponse(
                            username = response.data.username,
                            avatar = Constants.BASE_URL + avatar,
                            gender = response.data.gender,
                            nick_name = response.data.nick_name,
                            motto = response.data.motto
                        )
                        handleUserInfo(userInfo)
                        // 用户个人信息保存到内存
                        WeatherApplication.getGlobalContext()?.userInfo = userInfo
                        Toast.makeText(requireContext(), "获取用户信息成功", Toast.LENGTH_SHORT)
                            .show()
                    }
                } catch (e: Exception) {
                    // 非10000的响应，都会跑到catch这里
                    Toast.makeText(requireContext(), "获取用户信息失败", Toast.LENGTH_SHORT).show()
                    // 跳转到登录页面
                    startActivity(Intent(requireContext(), LoginActivity::class.java))
                    requireActivity().finish()
                    Log.e("MeFragment", "getUserInfo: ${e.message}")
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e("MeFragment", "getUserInfo: ${e.message}")
            Toast.makeText(requireContext(), "获取用户信息失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun handleUserInfo(userInfo: UserInfoResponse) {
        binding.tvAccount.text = userInfo.username
        binding.tvGender.text = userInfo.gender
        binding.tvNickname.text = userInfo.nick_name
        binding.tvSignature.text = userInfo.motto
        Glide.with(this@MeFragment).load(userInfo.avatar).into(binding.ivAvatar)
    }
}